//
//  AppController.m
//  YaTc
//
//  Created by Roberto on 17/02/09.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "AppController.h"
#import "TwitterCell.h"
#import "TwitterPost.h"
#import "TwitterManagement.h"


@implementation AppController

- (id) tableView: (NSTableView *) theTableView objectValueForTableColumn: (NSTableColumn *) tableColumn row: (int) index
{
	//NSLog(@"Returning object: %@", [twitterStatuses objectAtIndex:index]);
	return [twitterStatuses objectAtIndex:index];
}

- (int) numberOfRowsInTableView: (NSTableView *) theTableView
{
	//NSLog(@"Returning %d rows", [twitterStatuses count]);
	return [twitterStatuses count];
}

- (void) awakeFromNib
{
	
	[mainBox setContentView:loginView];
	//[mainBox setContentView:tweetsView];

	[NSTimer scheduledTimerWithTimeInterval:300 
							target:self selector:@selector(refreshTweetsTable) 
						  userInfo:nil repeats:YES];
	
	// TODO: COMENTAR Y QUITAR!!!!
	/*TwitterCell *cell = [[TwitterCell alloc] initWithUserLoggedIn:@"hylian"];	
	[column setDataCell:cell];
	twitterManagement = [[TwitterManagement alloc] initWithUser:@"hylian" password:@"****"];	
	[userLoggedInLbl setStringValue:@"User Logged In: hylian"];
	[self refreshTweetsTable];*/

}

- (IBAction) postNewTweetPressed: (id) sender
{
	[NSApp beginSheet:postNewTweetWindow
	   modalForWindow:[loading window]
		modalDelegate:nil
	   didEndSelector:NULL
		  contextInfo:NULL];
	[tweetTF setStringValue:@""];
  [charsLeftLbl setTextColor:[NSColor blackColor]];
	[charsLeftLbl setStringValue:@"140 of 140"];
}

- (IBAction) refreshButtonPressed: (id) sender
{
	//[twitterStatuses removeAllObjects];
	[self refreshTweetsTable];
}

- (IBAction) replyTweetPressed: (id) sender
{
	[NSApp beginSheet:postNewTweetWindow
	   modalForWindow:[loading window]
		modalDelegate:nil
	   didEndSelector:NULL
		  contextInfo:NULL];
	
	// Aqui hay que pillar el usuario seleccionado de la tabla.
	if ( [tableView selectedRow] != -1 )
	{
		TwitterPost *tp = [twitterStatuses objectAtIndex:[tableView selectedRow]];
		[tweetTF setStringValue:[NSString stringWithFormat:@"@%@", [tp userId]]];
		[charsLeftLbl setStringValue:[NSString stringWithFormat:@"%d of 140", (140 - [[tp userId] length] + 1)]];
	}
}

- (IBAction) sendTweet: (id) sender
{
	[twitterManagement postNewTweet:[tweetTF stringValue]];
	
	[NSApp endSheet:[tweetTF window]];
	[[tweetTF window] orderOut:sender];
}

- (IBAction) cancelTweet: (id) sender
{
	[NSApp endSheet:[tweetTF window]];
	[[tweetTF window] orderOut:sender];
}

- (IBAction) loginButtonPressed: (id) sender
{
	twitterUser = [userTF stringValue];
	twitterPassword = [passTF stringValue];
	NSLog(@"Loggin in with user: %@, password: *****", twitterUser);
	TwitterCell *cell = [[TwitterCell alloc] initWithUserLoggedIn:twitterUser];	
	[column setDataCell:cell];
	twitterManagement = [[TwitterManagement alloc] initWithUser:twitterUser password:twitterPassword];
	if ( ! [twitterManagement verifyCredentials] ) {
		[loginErrorLbl setHidden:NO];
	} else {
		[loginErrorLbl setHidden:YES];
		[mainBox setContentView:tweetsView];
		[userLoggedInLbl setStringValue:[NSString stringWithFormat:@"User Logged In: %@", twitterUser]];
		[self refreshTweetsTable];
	}
}

- (void) enableLoading
{
	[loading startAnimation:nil];
	[loading setHidden:NO];
}

- (void) disableLoading
{
	[loading stopAnimation:nil];
	[loading setHidden:YES];
}

- (void)controlTextDidChange:(NSNotification *)aNotification
{
	int charsLeft =  140 - [[tweetTF stringValue] length];
	if ( charsLeft < 0 ) {
		[charsLeftLbl setTextColor:[NSColor redColor]];
	} 
	else {
		[charsLeftLbl setTextColor:[NSColor blackColor]];
	}
	
	[charsLeftLbl setStringValue:[NSString stringWithFormat:@"%d of 140", charsLeft]];
}

- (void) refreshTweetsTable
{
	NSLog(@"Refreshing...");
	
	[self enableLoading];
	
	NSMutableArray *friendsPost = (NSMutableArray *)[twitterManagement getFriendsTimeLine];
	[friendsPost addObjectsFromArray:[twitterManagement getDirectMessages]];
	[friendsPost sortUsingSelector:@selector(compareDates:)];
	twitterStatuses = friendsPost;	
	[self disableLoading];
	NSDate *fecha = [NSDate date];
	NSString *fechaStr = [fecha descriptionWithCalendarFormat:@"%a %b %e, %H:%M:%S" timeZone:nil locale:nil];
	[lastUpdateLbl setStringValue:[NSString stringWithFormat:@"Last Update: %@",fechaStr]];
	[tableView reloadData];	
}
@end
